<template>
  <UploadExcel :on-success="handleSuccess" :before-upload="beforeUpload" />
</template>

<script>
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'
export default {
  name: 'Import',
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    // 上传之前 -> 判断文件大小
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 成功之后
    handleSuccess({ header, results }) {
      // 1. 读取excel表格转化为行和列的数据
      this.tableHeader = header
      this.tableData = results
      // 2. 数据格式转化 -> 中文转英文
      const data = this.transExcel(results)
      this.doImport(data)
      console.log('header', header, 'results', results)
    },
    // 中文转英文
    transExcel(data) {
      // 中英键名对应关系
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const results = data.map(zhObj => {
        const enObj = {} // 英文对象
        const zhKey = Object.keys(zhObj) // Object.keys(obj)方法 返回对象的所有键名的数组
        zhKey.forEach(zhKey => {
          const enKey = mapInfo[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            enObj[enKey] = new Date(formatExcelDate(zhObj[zhKey]))
          } else {
            enObj[enKey] = zhObj[zhKey]
          }
        })
        return enObj
      })
      return results
    },
    // 实现导入
    async doImport(data) {
      try {
        const res = await importEmployee(data)
        console.log('导入excel成功', res)
        this.$message.success('导入excel成功')
        // 回退
        this.$router.back()
      } catch (err) {
        console.log('导入excel失败,原因是', err)
        this.$message.error('导入excel失败')
      }
    }
  }
}
</script>
